//
//  MapGraph.cpp
//  DiceWar
//
//  Created by xiaofeng on 20/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "MapGraph.h"
#include <deque>
#include "HexCellCoordinate.h"
#include "MapTraverseCondition.h"

MapGraph::MapGraph()
: m_pHexMapGridMatrix(NULL) {}

MapGraph::~MapGraph() {}

void MapGraph::init(const HexMapGridMatrix* pHexMapGridMatrix)
{
    CCAssert(pHexMapGridMatrix, "Invalid parameter");
    m_pHexMapGridMatrix = pHexMapGridMatrix;
}

bool MapGraph::isGraphSinglePiece() const
{
    CCAssert(m_pHexMapGridMatrix, "The class is not initialized!");
    if (!m_pHexMapGridMatrix) return false;
    
    TraverseMatrix traverseMatrix;
    traverseMatrix.setAllValue(false);
    
    HexCellCoordinate root = getRoot(m_pHexMapGridMatrix, traverseMatrix, AvailableCellsTraverseCondition(m_pHexMapGridMatrix));
    if (!root.isValid()) return false;
    
    const int kSize = breadthFirstSearchOnMap(root.getX(), root.getY(), m_pHexMapGridMatrix, traverseMatrix);
    const int kNumAvailableCells = getNumAvailableCells();
    return kSize == kNumAvailableCells;
}

bool MapGraph::getFirstAvailableCellOnMap(int& coordinateX, int& coordinateY) const
{
    CCAssert(m_pHexMapGridMatrix, "The class is not initialized!");
    if (!m_pHexMapGridMatrix) return false;
    
    for (MapMatrixConstIter iter = m_pHexMapGridMatrix->begin(); iter != m_pHexMapGridMatrix->end(); ++iter)
    {
        if (!iter->isPlayable()) continue;
        HexCellCoordinate coordinate = iter->getCoordinate();
        
        coordinateX = coordinate.getX();
        coordinateY = coordinate.getY();
        return true;
    }
        
    return false;
}

int MapGraph::getLargestPieceSizeForPlayer(PlayerType type) const
{
    
}

int MapGraph::breadthFirstSearchOnMap(int rootX, int rootY, const HexMapGridMatrix* pHexMapGridMatrix, TraverseMatrix& traverseMatrix) const
{
    return bfs(rootX, rootY, traverseMatrix, AvailableCellsTraverseCondition(pHexMapGridMatrix));
}

int MapGraph::breadthFirstSearchOnPlayerCells(int rootX, int rootY, PlayerType player, const HexMapGridMatrix* pHexMapGridMatrix, TraverseMatrix& traverseMatrix) const
{
    return bfs(rootX, rootY, traverseMatrix, PlayerCellsTraverseCondition(pHexMapGridMatrix, player));
}

int MapGraph::getNumAvailableCells() const
{
    CCAssert(m_pHexMapGridMatrix, "The class is not initialized!");
    if (!m_pHexMapGridMatrix) return 0;
    
    int numAvailableCells = 0;
    HexMapGridMatrix::const_iterator iter = m_pHexMapGridMatrix->begin(); 
    for(; iter != m_pHexMapGridMatrix->end(); ++iter)
    {
        if (iter->isPlayable()) numAvailableCells++;
    }
    
    return numAvailableCells;
}